import * as api from "@/api";

export default {
  namespaced: true,

  state: {
    //  初始值设置为null, 因为新建的用户面值可能为空数组
    //  不方便我们判断
    isInitialed: false,
    boards: null,
  },

  getters: {
    getterBoard: ({ boards }) => (id) => {
      return Array.isArray(boards)
        ? boards.filter((item) => item.id === parseInt(id))
        : null;
    },
  },

  mutations: {
    updateBoards: (state, data) => {
      state.boards = data;
      state.isInitialed = true;
    },

    addBoards: (state, data) => {
      if (state.boards === null) {
        state.boards = [];
      }
      state.boards = [...state.boards, data];
    },
  },

  actions: {
    getBoards: async ({ commit }) => {
      let { data } = await api.getBoards();

      commit("updateBoards", data);
    },

    getBoard: async ({ commit }, id) => {
      let { data } = await api.getBoards(id);

      commit("updateBoards", data);
    },

    postBoard: async ({ commit }, data) => {
      await api.postBoard(data);

      let rs = await api.getBoards();

      commit("updateBoards", rs.data);
    },
  },
};
